<template>
    <el-dialog v-model="visible" title="选择要加载的工作流" width="50%">
        <div class="flow-list">
            <el-scrollbar max-height="400px">
                <!-- 加载状态 -->
                <div v-if="isLoading" style="text-align: center; padding: 20px;">
                    <i class="el-icon-loading" style="font-size: 24px;"></i>
                    <p>正在加载流程列表...</p>
                </div>

                <!-- 错误提示 -->
                <div v-else-if="loadError" style="color: red; text-align: center; padding: 20px;">
                    {{ loadError }}
                    <el-button @click="loadFlowList" type="text" style="margin-left: 10px;">重试</el-button>
                </div>

                <!-- 流程列表 -->
                <div v-else>
                    <el-input v-model="searchKeyword" placeholder="输入关键词搜索" style="margin-bottom: 10px;" />

                    <ul style="list-style: none; margin: 0; padding: 0;">
                        <li v-for="flow in filteredFlows" :key="flow.ID"
                            :class="['flow-item', { active: selectedFlowId === flow.ID }]"
                            @click="selectedFlowId = flow.ID"
                            style="padding: 12px; border-bottom: 1px solid #eee; cursor: pointer; display: flex; justify-content: space-between; align-items: center;">
                            {{ flow.Name }}
                            <el-button @click.stop="handleDelete(flow.ID)" type="danger" size="small">删除</el-button>
                        </li>
                    </ul>

                    <el-empty v-if="filteredFlows.length === 0" description="没有匹配的流程" />
                </div>
            </el-scrollbar>
        </div>
        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="confirmLoad">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import type { FlowListItem, FlowAPI } from '../types/types'
import { ElMessage, ElMessageBox, ElDialog, ElScrollbar, ElEmpty } from 'element-plus'

const props = defineProps<{
    modelValue: boolean
    api?: FlowAPI
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'load', id: string): void
}>()

const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const searchKeyword = ref('')
const selectedFlowId = ref<number | null>(null)
const savedFlows = ref<FlowListItem[]>([]) // 存储流程列表
const isLoading = ref(false)
const loadError = ref<string | null>(null)

// 从 api 获取流程列表
const loadFlowList = async () => {
    if (!props.api?.getFlowList) return

    isLoading.value = true
    loadError.value = null

    try {
        const list = await props.api.getFlowList()
        savedFlows.value = list.data
    } catch (error) {
        loadError.value = '加载流程失败，请稍后再试。'
        ElMessage.error('加载流程失败')
    } finally {
        isLoading.value = false
    }
}

let lastFetchTime = 0
const DEBOUNCE_TIME = 5000 // 5秒内不再重复请求

watch(
    () => visible.value,
    async (newVal) => {
        if (newVal) {
            const now = Date.now()
            if (now - lastFetchTime > DEBOUNCE_TIME) {
                await loadFlowList()
                if (savedFlows.value.length > 0) {
                    selectedFlowId.value = savedFlows.value[0].id
                }
                lastFetchTime = now
            }
        }
    }
)

const filteredFlows = computed(() => {
    const flows = Array.isArray(savedFlows.value) ? savedFlows.value : []

    if (!searchKeyword.value) {
        return flows
    }

    const keyword = searchKeyword.value.toLowerCase()

    return flows.filter(flow =>
        flow.Name.toLowerCase().includes(keyword)
    )
})

const confirmLoad = () => {
    if (selectedFlowId.value) {
        emit('load', selectedFlowId.value)
        visible.value = false
    }
}

const handleDelete = async (id: number) => {
    try {
        await ElMessageBox.confirm('确定要删除该流程吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        if (!props.api?.deleteFlow) {
            ElMessage.error('未配置删除接口');
            return;
        }

        await props.api.deleteFlow({ "id": id });
        ElMessage.success('删除成功');

        // 刷新流程列表
        savedFlows.value = savedFlows.value.filter(flow => flow.ID !== id);

    } catch (error) {
        ElMessage.error('删除失败');
    }
};
</script>

<style scoped>
.flow-item {
    transition: background-color 0.3s;
}

.flow-item:hover {
    background-color: #f5f7fa;
}

.flow-item.active {
    background-color: #ecf5ff;
    border-left: 3px solid #409EFF;
}
</style>